package controller

import (
	"fmt"
	"htdemo.com/goim/logic/dao"
	"htdemo.com/goim/logic/model"
	"htdemo.com/goim/public/imerror"
	"htdemo.com/goim/public/logger"
	"net/http"
	"strconv"
	"strings"
)

func init() {
	g := Engine.Group("/message")
	g.GET("list", handler(MessageController{}.list))
	g.POST("read", handler(MessageController{}.read))
}

type MessageController struct{}

func (MessageController) list(c *context) {
	receiverIdStr := c.Query("receiver_id")
	receiverId, _ := strconv.Atoi(receiverIdStr)
	if receiverId == 0 {
		c.JSON(http.StatusOK, NewWithBError(imerror.LErrInvalidParams))
		return
	}
	ctx := Context()
	messages, err := dao.MessageDao.List(ctx, int(c.userId), int(c.userId), receiverId, 10)
	params := ""
	//var tempList []*model.Message
	for _, v := range messages {
		params = fmt.Sprintf("%s%d,", params, v.MessageId)
		//tempList = append()
	}
	if len(messages) > 0 {
		params = strings.TrimSuffix(params, ",")
		err = dao.MessageDao.UpdateUnreadMessage(ctx, params)
		if err != nil {
			logger.Sugar.Error(err)
			c.response(nil, err)
			return
		}
	}
	length := len(messages)
	for i := 0; i < length/2; i++ {
		temp := messages[length-1-i]
		messages[length-1-i] = messages[i]
		messages[i] = temp
	}
	c.response(messages, err)
}

func (MessageController) read(c *context) {
	var r model.ReadReq
	c.bindJson(&r)
	if len(r.MessageIds) == 0 {
		c.JSON(http.StatusOK, NewWithBError(imerror.LErrInvalidParams))
		return
	}
	r.MessageIds = strings.TrimSpace(r.MessageIds)
	c.response(nil, dao.MessageDao.UpdateUnreadMessage(Context(), r.MessageIds))
}
